﻿using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {
	
	public float speed = 0.1f;
	public float lifetimeInS = 3.0f;
	public GameObject explodePrefab;

	private float ageInS = 0.0f;
	private Vector3 initDirection = Vector3.forward;
	private string targetTag = "";

	// Use this for initialization
	void Start () {
		ageInS = 0.0f;
	}

	public void SetTarget(string targetTag) {
		this.targetTag = targetTag;
	}

	public void Lunch(Vector3 position, Vector3 direction) {
		gameObject.transform.position = position;
		initDirection = direction;
	}
	
	// Update is called once per frame
	void Update () {
		gameObject.transform.Translate(initDirection * speed * Time.deltaTime);
		ageInS += Time.deltaTime;
		if (ageInS > lifetimeInS) {
			// explode or disappear
			disappear();
		}
	}

	void OnTriggerEnter(Collider e) {
		if(e.gameObject.tag.CompareTo(targetTag) == 0) {
			explode();
			makeHurt(e.gameObject);
			Debug.Log("explode.");
		}
	}

	private void makeHurt(GameObject hitGameObject) {
		LifePackage lifePackage = hitGameObject.GetComponent<LifePackage>();
		if (lifePackage) {
			lifePackage.GetHurt();
		}
	}

	private void disappear() {
		Destroy(gameObject);
	}

	private void explode() {
		if (explodePrefab) {
			GameObject explode = Instantiate<GameObject>(explodePrefab);
			explode.transform.position = transform.position;
		}
		GameObject.Destroy(gameObject);
	}
}
